package com.baijia.services;

import com.alibaba.fastjson.JSONObject;
import com.baijia.dao.AuthorizeServiceDao;
import com.baijia.dao.po.AuthorizeService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.annotation.PostConstruct;

/**
 * @title AuthorizeServiceManager
 * @desc 管理注册的业务系统
 * @author caoliang
 * @date 2015年12月5日
 * @version 1.0
 */
@Component
public class AuthorizeServiceManager {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Value("${passport.env:prod}")
    private String env;
    @Autowired
    private AuthorizeServiceDao authorizeServiceDao;

    private List<AuthorizeService> services = new CopyOnWriteArrayList<>();

    private Date lastTrigger;

    public List<AuthorizeService> getServices() {
        return services;
    }

    @PostConstruct
    public void init() {
        services.addAll(authorizeServiceDao.getAllAuthorizeServices(env));
        lastTrigger = new Date();
        log.info(JSONObject.toJSONString(services));
    }

    // 3分钟去扫一次库表，看到新的数据加载进来
    @Scheduled(initialDelay = 3 * 60 * 1000, fixedRate = 3 * 60 * 1000)
    public void findNewAuthorizedServices() {
        Date cur = new Date();
        Collection<AuthorizeService> newServices =
            authorizeServiceDao.getAuthorizeServicesHaveBeenChangeSinceLastTrigger(lastTrigger, env);
        if (!CollectionUtils.isEmpty(newServices)) {
            for (AuthorizeService authorizeService : services) {
                for (AuthorizeService newService : newServices) {
                    if (authorizeService.getId() == newService.getId()) {
                        services.remove(authorizeService);
                    }
                }
            }
            services.addAll(newServices);
        }
        lastTrigger = cur;
    }
}
